/**
 * @description 瓦片服务
*/

const { JSONFile, StoreFile } = require('@daelui/oxkit/dist/index.js')
const Service = require('../service.js')
const Tianditu = require('./tianditu.js')
const Autonavi = require('./autonavi.js')
const ArcGis = require('./arcgis.js')
const OSM = require('./osm.js')
const Google = require('./google.js')
const config = global.config
const tile = config.tile || {}
const maps = tile.maps || []

// 下载器集合
const loaderEntries ={
  tianditu: Tianditu,
  autonavi: Autonavi,
  arcgis: ArcGis,
  osm: OSM,
  google: Google
}

// 瓦片服务
class Tile extends Service {
  constructor () {
    super()
    this.tasks = []
  }

  // 创建任务
  createTask (req) {
    return this.solveRequest(req).then(data => {
      let params = data.params || {}
      let result = null
      // 参数检查
      let layers = Array.isArray(params.layers) ? params.layers : []
      // 获取有效的图层
      let allowLayers = layers.filter(item => {
        let b = false
        maps.forEach(node => {
          if (node.map === item.map){
            let matched = node.layers.find(layer => layer.layer === item.layer && layer.path === item.path)
            if (matched) {
              b = true
              item.mapProvider = node
              item.layerProvider = matched
            }
          }
        })
        return b
      })
      if (!params.layers || params.layers.length < 1) {
        result = this.result({
          success: 0,
          msg: '未选择地图图层'
        })
      } else if (allowLayers.length < 1) {
        result = this.result({
          success: 0,
          msg: '不支持该地图瓦片下载'
        })
      } else if (!params.range || params.range.length !== 4) {
        result = this.result({
          success: 0,
          msg: '坐标范围不完整'
        })
      } else if (!params.levels || params.levels.length < 1) {
        result = this.result({
          success: 0,
          msg: '未选择地图级别'
        })
      }
      if (result) {
        return result
      }

      // 开始任务
      allowLayers.forEach(item => {
        this.start(item, params)
      })

      return this.result({
        success: 1,
        msg: '任务执行中'
      })
    })
  }

  // 下载地图
  start (layer, params) {
    let Loader = loaderEntries[layer.map]
    if (Loader) {
      let task = new Loader({
        params: params,
        layer: layer
      })
      this.tasks.push(task)
      task.run()
    }
  }

  // 停止
  stop (req) {
    return this.solveRequest(req).then(data => {
      let params = data.params || {}
      this.tasks.forEach(item => {
        item.stop()
      })
      return this.result({
        success: 1,
        msg: '操作成功'
      })
    })
  }

  // 查询任务
  query () {
    let res = new JSONFile().read(tile.taskPath + '/tile_db.json')
    let data = res.data || []
    return this.result({
      success: 1,
      msg: '成功',
      data
    })
  }

  // 停止指定任务
  stopTask (req) {
    return this.solveRequest(req).then(data => {
      let params = data.params || {}
      let query = data.query || {}
      let routeParams = req.routeParams || {}
      let key = routeParams.key || params.key || query.key || ''
      
      if (!key) {
        return this.result({
          success: 0,
          msg: '任务标识不能为空'
        })
      }

      // 查找并停止指定任务
      let task = this.tasks.find(item => {
        let taskKey = item.layer.map + '/' + item.layer.path
        return taskKey === key
      })

      if (task) {
        task.stop()
        return this.result({
          success: 1,
          msg: '任务已停止'
        })
      } else {
        // 如果任务不在运行中，更新任务状态
        this.updateTaskStatus(key, { status: 0 })
        return this.result({
          success: 1,
          msg: '任务已停止'
        })
      }
    })
  }

  // 恢复任务
  resumeTask (req) {
    return this.solveRequest(req).then(data => {
      let params = data.params || {}
      let query = data.query || {}
      let routeParams = req.routeParams || {}
      let key = routeParams.key || params.key || query.key || ''
      
      if (!key) {
        return this.result({
          success: 0,
          msg: '任务标识不能为空'
        })
      }

      // 从存储中恢复任务
      let store = new JSONFile().read(tile.taskPath + '/tile_db.json')
      let taskItem = null
      if (store.data && store.data.list) {
        taskItem = store.data.list.find(item => item.key === key)
      }
      let taskData = taskItem ? taskItem.value : null
      
      if (!taskData) {
        return this.result({
          success: 0,
          msg: '任务不存在'
        })
      }

      // 检查任务是否已完成
      let successCount = taskData.tiles.filter(item => item.success === 1).length
      if (successCount >= taskData.sum) {
        return this.result({
          success: 0,
          msg: '任务已完成'
        })
      }

      // 检查是否已有运行中的任务
      let existingTask = this.tasks.find(item => {
        let taskKey = item.layer.map + '/' + item.layer.path
        return taskKey === key
      })

      if (existingTask) {
        // 如果任务已在运行，直接恢复
        existingTask.resume()
        return this.result({
          success: 1,
          msg: '任务已恢复'
        })
      }

      // 重新启动任务
      let layer = {
        map: taskData.map,
        path: taskData.path,
        mapProvider: this.getMapProvider(taskData.map),
        layerProvider: this.getLayerProvider(taskData.map, taskData.path)
      }

      if (layer.mapProvider && layer.layerProvider) {
        // 创建新任务实例，但使用现有数据
        let Loader = loaderEntries[layer.map]
        if (Loader) {
          let task = new Loader({
            params: {
              range: taskData.range,
              levels: taskData.levels
            },
            layer: layer
          })
          // 设置现有数据
          task.data = taskData
          task.store = new StoreFile({
            path: tile.taskPath,
            key: 'tile_db'
          })
          this.tasks.push(task)
          // 只恢复未完成的下载
          task.resume()
        }
        
        return this.result({
          success: 1,
          msg: '任务已恢复'
        })
      } else {
        return this.result({
          success: 0,
          msg: '不支持该地图瓦片下载'
        })
      }
    })
  }

  // 删除任务
  deleteTask (req) {
    return this.solveRequest(req).then(data => {
      let params = data.params || {}
      let query = data.query || {}
      let routeParams = req.routeParams || {}
      let key = routeParams.key || params.key || query.key || ''
      
      if (!key) {
        return this.result({
          success: 0,
          msg: '任务标识不能为空'
        })
      }

      // 停止运行中的任务
      let task = this.tasks.find(item => {
        let taskKey = item.layer.map + '/' + item.layer.path
        return taskKey === key
      })

      if (task) {
        task.stop()
        // 从任务列表中移除
        let index = this.tasks.indexOf(task)
        if (index > -1) {
          this.tasks.splice(index, 1)
        }
      }

      // 从存储中删除任务数据
      let store = new JSONFile().read(tile.taskPath + '/tile_db.json')
      if (store.data && store.data.list) {
        let taskIndex = store.data.list.findIndex(item => item.key === key)
        if (taskIndex !== -1) {
          store.data.list.splice(taskIndex, 1)
          new JSONFile().write(tile.taskPath + '/tile_db.json', store.data)
        }
      }

      return this.result({
        success: 1,
        msg: '任务已删除'
      })
    })
  }

  // 更新任务状态
  updateTaskStatus (key, status) {
    let store = new JSONFile().read(tile.taskPath + '/tile_db.json')
    if (store.data && store.data.list) {
      let taskItem = store.data.list.find(item => item.key === key)
      if (taskItem && taskItem.value) {
        Object.assign(taskItem.value, status)
        new JSONFile().write(tile.taskPath + '/tile_db.json', store.data)
      }
    }
  }

  // 获取地图提供商
  getMapProvider (mapName) {
    return maps.find(node => node.map === mapName)
  }

  // 获取图层提供商
  getLayerProvider (mapName, layerPath) {
    let mapProvider = this.getMapProvider(mapName)
    if (mapProvider) {
      return mapProvider.layers.find(layer => layer.path === layerPath)
    }
    return null
  }
}

module.exports = Tile